<template>
	<view class="container">
		<!-- Top scanning section -->
		<view class="top-section">
			<view class="scan-section">
				<!-- <view class="scan-title">扫描托盘</view> -->
				<view class="s-input-box flex-row-between s-w">
					<input 
						auto-focus="true" 
						v-model="scanCode" 
						@confirm="handleScan" 
						class="s-input scan-input flex1" 
						placeholder="请输入或扫描托盘号"
						:disabled="loading"
					/>
					<image v-if="scanCode" class="s-input-icon clear-icon" src="/static/images/clear.png" @click="clearScanCode"></image>
					<image class="s-input-icon s-i" src="/static/images/scan.png"></image>
				</view>
			</view>

			<!-- Order info section -->
			<view class="info-section" v-if="orderInfo.orderNo">
				<view class="info-item">
					<text class="info-label">订单号：</text>
					<text class="info-value">{{ orderInfo.orderNo }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">托盘号：</text>
					<text class="info-value">{{ orderInfo.trayNo }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">总数：</text>
					<text class="info-value">{{ orderInfo.total }}</text>
				</view>
			</view>
		</view>

		<!-- Loading state -->
		<view class="loading-container" v-if="loading">
			<view class="loading-spinner"></view>
			<text class="loading-text">加载中...</text>
		</view>

		<!-- Materials list -->
		<scroll-view 
			scroll-y 
			class="materials-list" 
			v-else-if="materials.length"
			:refresher-enabled="true"
			@refresherrefresh="handleRefresh"
			:refresher-triggered="refreshing"
		>
			<view class="material-card" v-for="(item, index) in materials" :key="index">
				<!-- <view class="material-header">物料信息</view> -->
				<view class="material-content">
					<view class="material-row">
						<text class="label">出库单号</text>
						<text class="value">{{ item.relOrderNo }}</text>
					</view>
					<view class="material-row">
						<text class="label">目的地信息</text>
						<text class="value">{{ item.address }}</text>
					</view>
					<view class="material-row">
						<text class="label">SKU编号</text>
						<text class="value">{{ item.productNo }}</text>
					</view>
					<view class="material-row">
						<text class="label">物料名称</text>
						<text class="value">{{ item.productName }}</text>
					</view>
					
					<view class="material-row">
						<text class="label">数量</text>
						<text class="value">{{ item.qty }}</text>
					</view>
					<view class="material-row">
						<text class="label">单位</text>
						<text class="value">{{ item.productUnit }}</text>
					</view>
					
				</view>
			</view>
		</scroll-view>

		<!-- Empty state -->
		<view class="nodata-label" v-else>
			<text class="label">暂无托盘信息</text>
		</view>

		<!-- Bottom actions -->
		<view class="fixed-bottom">
			<view 
				@click="finalStock" 
				class="botton p-botton font-30"
				style="height: 92rpx; line-height:92rpx;margin: 50rpx 0rpx;"
			>
				最终出库
			</view>
			<button 
				class="submit-btn" 
				@tap="handleSubmit"
			>
				{{ loading ? '处理中...' : '打 印' }}
			</button>
		</view>
	</view>
</template>

<script>
	import {
		initPrinter,
		closePrinter,
		printProductLabel,
		SPDAPrintTailLabel,
		printTailLabel
	} from "@/utils/print.js"
	import { getRecordByNo, finalOutStock, addRecord } from "./api"
	const printer = uni.requireNativePlugin('LcPrinter');	
	export default {
		data() {
			return {
				scanCode: '',
				orderInfo: {
					orderNo: '',
					trayNo: ''
				},
				materials: [],
				printerInitialized: false,
				loading: false,
				refreshing: false,
				error: null
			};
		},
		computed: {
			canSubmit() {
				return this.orderInfo.trayNo && this.orderInfo.orderNo && this.materials.length > 0;
			}
		},
		onLoad() {
			this.initializePrinter();
		},
		onUnload() {
			this.closePrinter();
		},
		methods: {
			// 初始化打印机
			async initializePrinter() {
				try {
					this.loading = true;
					const result = await printer.initPrinter({});
					this.printerInitialized = true;
				} catch (error) {
					console.error('打印机初始化失败:', error);
					this.$modal.confirmClose("打印机初始化失败，请检查设备连接");
					this.printerInitialized = false;
				} finally {
					this.loading = false;
				}
			},
			
			// 关闭打印机
			async closePrinter() {
				try {
					await closePrinter();
				} catch (error) {
					console.error('关闭打印机失败:', error);
				}
			},
			
			// 检查打印机状态
			checkPrinterStatus() {
				if (!this.printerInitialized) {
					this.$modal.confirmClose("打印机未初始化，请先初始化打印机");
					return false;
				}
				return true;
			},
			
			// 处理打印
			async handleSubmit() {
				// if (!this.checkPrinterStatus() || !this.canSubmit) {
				// 	return;
				// }
				
				try {
					this.loading = true;
					let params = this.materials[0];
					params.trayNo = this.scanCode;
					
					// 先执行打印
					const printData = this.materials[0];
					await printTailLabel(printData);
					
					// 打印成功后再调用addRecord
					let res = await addRecord(params);
					if(res.code == 200){
						this.$modal.msgSuccess("操作成功");
						uni.$emit('refreshList', { msg: '页面更新' });
						this.clearScanCode();
					} else {
						res.msg && this.$modal.confirmClose(res.msg);
					}
				} catch (error) {
					console.error('操作失败:', error);
					this.$modal.confirmClose("操作失败，请检查打印机连接");
				} finally {
					this.loading = false;
				}
			},

			// 处理扫描
			async handleScan() {
				if(!this.scanCode){
					this.$modal.msg("请输入正确托盘号");
					return;
				}

				try {
					this.loading = true;
					const res = await getRecordByNo(this.scanCode);
					
					if(res.code == 200){
						if(res.data && res.data[0]){
							this.orderInfo.orderNo = res.data[0].relOrderNo;
							this.orderInfo.trayNo = res.data[0].trayNo;
							this.orderInfo.total = res.data.reduce((acu,pre) => {
								return acu+pre.qty
							},0) 
							this.materials = res.data;
						} else {
							this.$modal.msg("未找到相关托盘信息");
						}
					} else {
						res.msg && this.$modal.confirmClose(res.msg);
					}
				} catch (error) {
					console.error('获取托盘信息失败:', error);
					this.$modal.confirmClose("获取托盘信息失败，请重试");
				} finally {
					this.loading = false;
				}
			},

			// 最终出库
			async finalStock() {
				if (!this.canSubmit) {
					this.$modal.msg("请先扫描托盘");
					return;
				}

				try {
					await this.$modal.confirm('确定要执行最终出库操作吗？');
					this.loading = true;
					
					const res = await finalOutStock({
						trayNo: this.orderInfo.trayNo
					});
					
					if (res.code == 200) {
						// await this.handleSubmit();
						this.$modal.msgSuccess("操作成功");
					} else {
						res.msg && this.$modal.confirmClose(res.msg);
					}
				} catch (error) {
					console.error('最终出库失败:', error);
					this.$modal.confirmClose("最终出库失败，请重试");
				} finally {
					this.loading = false;
				}
			},

			// 清除扫描码
			clearScanCode() {
				this.scanCode = '';
				this.orderInfo = {
					orderNo: '',
					trayNo: ''
				};
				this.materials = [];
			},

			// 处理下拉刷新
			async handleRefresh() {
				if (this.scanCode) {
					this.refreshing = true;
					await this.handleScan();
					this.refreshing = false;
				}
			}
		}
	}
</script>

<style lang="scss">
	.container {
		min-height: 100vh;
		background-color: #F0F2F5;
		position: relative;
		padding-bottom: 240rpx;

		.top-section {
			padding: 30rpx 20rpx;
			background: linear-gradient(180deg, #99cfd6 0%, #4599ad 100%) !important;
		}

		.scan-section {
			background-color: #FFFFFF;
			padding: 24rpx;
			border-radius: 16rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
			margin-bottom: 20rpx;

			.scan-title {
				font-size: 28rpx;
				color: #333;
				margin-bottom: 16rpx;
				font-weight: 500;
			}
		}

		.scan-input {
			background-color: #F8F9FA;
			height: 80rpx;
			padding: 0 24rpx;
			border-radius: 8rpx;
			font-size: 28rpx;
			border: 2rpx solid #E5E6EB;

			&::placeholder {
				color: #C9CDD4;
			}

			&:disabled {
				background-color: #F5F5F5;
				color: #999;
			}
		}

		.info-section {
			background-color: #FFFFFF;
			padding: 24rpx;
			border-radius: 16rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

			.info-item {
				display: flex;
				align-items: center;
				margin-bottom: 16rpx;

				&:last-child {
					margin-bottom: 0;
				}

				.info-label {
					font-size: 28rpx;
					color: #666;
					width: 120rpx;
				}

				.info-value {
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
				}
			}
		}

		.loading-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 40rpx;

			.loading-spinner {
				width: 60rpx;
				height: 60rpx;
				border: 4rpx solid #f3f3f3;
				border-top: 4rpx solid #4599ad;
				border-radius: 50%;
				animation: spin 1s linear infinite;
			}

			.loading-text {
				margin-top: 20rpx;
				color: #666;
				font-size: 28rpx;
			}
		}

		.materials-list {
			padding: 20rpx;
			max-height: calc(100vh - 600rpx);

			.material-card {
				background-color: #FFFFFF;
				border-radius: 16rpx;
				margin-bottom: 20rpx;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
				overflow: hidden;

				.material-header {
					padding: 20rpx 24rpx;
					background-color: #F8F9FA;
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
					border-bottom: 2rpx solid #E5E6EB;
				}

				.material-content {
					padding: 24rpx;
				}

				.material-row {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 16rpx;
					font-size: 28rpx;

					&:last-child {
						margin-bottom: 0;
					}

					.label {
						color: #666;
					}

					.value {
						color: #333;
						font-weight: 500;
					}
				}
			}
		}

		.fixed-bottom {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: #FFFFFF;
			padding: 24rpx 20rpx;
			box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);

			.bottom-section {
				margin-bottom: 24rpx;

				.scan-title {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 16rpx;
					font-weight: 500;
				}
			}

			.botton {
				&.disabled {
					opacity: 0.5;
					pointer-events: none;
				}
			}
		}

		.submit-btn {
			height: 88rpx;
			line-height: 88rpx;
			background: #4599ad;
			color: #FFFFFF;
			border-radius: 10rpx;
			font-size: 32rpx;
			text-align: center;
			font-weight: 500;
			box-shadow: 0 4rpx 12rpx rgba(46, 92, 254, 0.3);

			&:active {
				transform: scale(0.98);
			}

			&:disabled {
				background: #ccc;
				box-shadow: none;
			}
		}
	}

	.nodata-label {
		text-align: center;
		margin-top: 40rpx;
		color: #999999;
	}
	.s-input-box {
			position: relative;
			display: flex;
			align-items: center;
			
			.s-input {
				padding-right: 80rpx; // 为右侧图标留出空间
			}
			
			.s-input-icon {
				position: absolute;
				width: 32rpx;
				height: 32rpx;
				right: 24rpx;
				z-index: 1;
				
				&.clear-icon {
					right: 70rpx; // 清除图标位置
				}
				
				&.s-i {
					right: 24rpx; // 扫描图标位置
				}
			}
		}

	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
</style>